package com.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.*;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @program: tycd
 * @description: Http请求工具类
 * @author: jiayingliu
 * @create:
 **/
@SuppressWarnings("deprecation")
@Slf4j
public class HttpUtils {
    /**
     * @param @param  reqUrl
     * @param @param  params
     * @param @return
     * @param @throws Exception
     * @Description: http get请求共用方法
     * @date
     */

    @SuppressWarnings("resource")
    public static String sendGet(String reqUrl, Map<String, String> params, String token)
            throws Exception {
        String result = "";
        /*     InputStream inputStream = null;*/
        HttpGet request = new HttpGet();
        try {
            String url = buildUrl(reqUrl, params, token);
            System.out.println("路径为：" + url);
            //去除特殊字符
            URL url1 = new URL(url);
            URI uri = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
            HttpClient client = new DefaultHttpClient();
            request.setHeader("Accept-Encoding", "gzip");
            request.setURI(uri);
            request.setHeader("Authorization", token);

            //通过对象获得响应对象
            HttpResponse response = client.execute(request);

            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            }
            return result;
        } finally {

            request.releaseConnection();
        }
    }

    public static String HttpPostWithJson(String url, String json) {
        String returnValue = "这是默认返回值，接口调用失败";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try{
            //第一步：创建HttpClient对象
            httpClient = HttpClients.createDefault();

            //第二步：创建httpPost对象
            HttpPost httpPost = new HttpPost(url);

            //第三步：给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(json,"utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);

            //第四步：发送HttpPost请求，获取返回值
            returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时，必须用此方法

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //第五步：处理返回值
        return returnValue;
    }



    public static String doGet(String url) {
        try {
            HttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());

                return strResult;
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * @param @param  reqUrl
     * @param @param  params
     * @param @return
     * @param @throws Exception
     * @Description: http post请求共用方法
     */

    public static String sendPost(String reqUrl, Map<String, String> params, String token)
            throws Exception {
        String result = "";
        try {
            Set<String> set = params.keySet();
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (String key : set) {
                list.add(new BasicNameValuePair(key, params.get(key)));
            }
            if (list.size() > 0) {
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpPost request = new HttpPost(reqUrl);

                    request.setHeader("Accept-Encoding", "gzip");
                    request.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                    request.setHeader("Authorization", token);
                    HttpResponse response = client.execute(request);
                    System.out.println(response);
                    try {
                        // 判断网络连接状态码是否正常(0--200都数正常)
                        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                            result = EntityUtils.toString(response.getEntity(), "utf-8");
                        }
                        return result;
                    } finally {
                        request.releaseConnection();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new Exception("网络连接失败,请连接网络后再试");
                }
            } else {
                throw new Exception("参数不全，请稍后重试");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception("发送未知异常");
        }
    }


/**
*发送文件
*
**/
    public static String sendPostWithFile(String reqUrl, MultipartEntityBuilder multipartEntityBuilder) {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(reqUrl);// 请求地址
//        MultipartEntityBuilder meb = MultipartEntityBuilder.create();
//        ContentType strContent = ContentType.create("application/zip", Charset.forName("UTF-8"));
//        meb.addBinaryBody("uploadfile", new File("D://文件.zip"));// 文件路径
//        meb.addTextBody("fileName", "文件.zip", strContent);// 文件名
//        meb.addTextBody("sendMailName", "主标题", strContent);
//        meb.addTextBody("mailSubject", "子标题", strContent);
//        meb.addTextBody("receiveMail", "anyf@kunyitech.com", strContent);//多个以;分割
//        meb.addTextBody("mailContent", "邮件内容", strContent);
        HttpEntity httpEntity = multipartEntityBuilder.build();
        httpPost.setEntity(httpEntity);
        try {
            StringBuilder sb = new StringBuilder();
            String line;
            HttpResponse httpResponse = httpClient.execute(httpPost);
            InputStream inputStream = httpResponse.getEntity().getContent();
//            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
//            return URLDecoder.decode(sb.toString(),StandardCharsets.UTF_8.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param @param  urls
     * @param @param  params
     * @param @return
     * @Description: http post请求json数据
     */

    public static String sendPostBuffer(String urls, String params, String token)
            throws ClientProtocolException, IOException {
        HttpPost request = new HttpPost(urls);

        StringEntity se = new StringEntity(params, HTTP.UTF_8);
        request.setEntity(se);
        // 发送请求
        @SuppressWarnings("resource")
        HttpResponse httpResponse = new DefaultHttpClient().execute(request);
        // 得到应答的字符串，这也是一个 JSON 格式保存的数据
        String retSrc = EntityUtils.toString(httpResponse.getEntity());
        request.releaseConnection();
        return retSrc;

    }


    /**
     * @param @param  urlStr
     * @param @param  xmlInfo
     * @param @return
     * @Description: http请求发送xml内容
     */

    public static String sendXmlPost(String urlStr, String xmlInfo, String token) {
        // xmlInfo xml具体字符串

        try {
            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            con.setRequestProperty("Pragma:", "no-cache");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml");
            OutputStreamWriter out = new OutputStreamWriter(
                    con.getOutputStream());
            out.write(new String(xmlInfo.getBytes("utf-8")));
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String lines = "";
            for (String line = br.readLine(); line != null; line = br
                    .readLine()) {
                lines = lines + line;
            }
            return lines; // 返回请求结果
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "fail";
    }

    /**
     * 发送POST请求
     *
     * @param url        目的地址
     * @param parameters 请求参数，Map类型。
     * @return 远程响应结果
     */
    public static String sendPostBody(String url, Map<String, String> parameters, Map<String, Object> jsonObject) {
        String result = "";// 返回的结果
        BufferedReader in = null;// 读取响应输入流
        PrintWriter out = null;
        StringBuffer sb = new StringBuffer();// 处理请求参数
        String params = "";// 编码之后的参数
        HttpResponse response = null;
        HttpClient httpClient = new DefaultHttpClient();
        // 编码请求参数
        if (parameters.size() == 1) {
            for (String name : parameters.keySet()) {
                try {
                    sb.append(name).append("=").append(java.net.URLDecoder.decode(parameters.get(name), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            params = sb.toString();
        } else {
            for (String name : parameters.keySet()) {
                try {
                    sb.append(name).append("=").append(java.net.URLDecoder.decode(parameters.get(name), "UTF-8")).append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            String temp_params = sb.toString();
            params = temp_params.substring(0, temp_params.length() - 1);
        }
        String full_url = url + "?" + params;
        System.out.println("路径：       " + full_url);

        HttpPost httpPost = new HttpPost(full_url);
        List<NameValuePair> nameValuePairs = buildValuePair(jsonObject);
        HttpEntity httpEntity = new UrlEncodedFormEntity(nameValuePairs, Charset.forName("utf-8"));
        httpPost.setEntity(httpEntity);
        // 获取请求返回
        try {
            response = httpClient.execute(httpPost, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 构建get方式的url
     *
     * @param reqUrl 基础的url地址
     * @param params 查询参数
     * @return 构建好的url
     */

    public static String buildUrl(String reqUrl, Map<String, String> params, String token) {
        StringBuilder query = new StringBuilder();
        Set<String> set = params.keySet();
        for (String key : set) {
            query.append(String.format("%s=%s&", key, params.get(key)));
        }
        String param = query.substring(0, query.length() - 1);
        System.out.println("requestUrl：" + reqUrl);
        System.out.println("requestParams：" + param);
        return reqUrl + "?" + param;
    }


    /**
     * @description: 构建post方式的param
     * @param: params
     * @return: 集合键值
     */
    private static List<NameValuePair> buildValuePair(Map<String, Object> params) {
        Set<NameValuePair> nameValuePairs = new HashSet<>();
        if (null != params) {
            for (Map.Entry entry : params.entrySet()) {
                if (null != entry.getValue()) {
                    nameValuePairs.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
                }
            }
        }
        return new ArrayList<>(nameValuePairs);
    }
}